import { Button, Checkbox, Form, Input } from "antd";
import { useNavigate } from "react-router-dom";
import "./Login.css";
import { useDispatch } from "react-redux";
import { updateBase } from "../../store/baseSlice";

const Login2 = () => {
  const [form] = Form.useForm();

  const dispatch = useDispatch();
 
  const userInfo =  localStorage.getItem("userInfo");

  const navigate = useNavigate();

  window.addEventListener('load',()=>{
    if(userInfo){
      const {username,password} = JSON.parse(userInfo);
      form.setFieldValue("username",username);
      form.setFieldValue("password",password);
    }
  })

  const onFinish = (values) => {
    const username = values.username;
    const password = values.password;
    const data = { username, password };
    if (values.remember) {
      localStorage.setItem("userInfo", JSON.stringify(data));
      console.log(data);
    }else{
      localStorage.removeItem("userInfo");
    }
    if (username === "admin" && password === "123456") {
      // tk设置为true，表示已经登录
      dispatch(updateBase(true));
      navigate("/");
    } else {
      alert("用户名或密码错误！请重新输入");
    }
  };
  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <div className="login-form" >
      <div>
    <Form
      form={form}
      name="login"
      labelCol={{
        span: 8,
      }}
      wrapperCol={{
        span: 16,
      }}
      style={{
        maxWidth: 600,
      }}
      initialValues={{
        remember: true,
      }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        label="用户名"
        name="username"
        rules={[
          {
            required: true,
            message: "Please input your username!",
          },
        ]}
      >
        <Input />
      </Form.Item>

      <Form.Item
        label="密码"
        name="password"
        rules={[
          {
            required: true,
            message: "Please input your password!",
          },
        ]}
      >
        <Input.Password />
      </Form.Item>

      <Form.Item
        name="remember"
        valuePropName="checked"
        wrapperCol={{
          offset: 8,
          span: 16,
        }}
      >
        <Checkbox>记住密码</Checkbox>
      </Form.Item>

      <Form.Item
        wrapperCol={{
          offset: 8,
          span: 16,
        }}
      >
        <Button type="primary" htmlType="submit">
          提交
        </Button>
      </Form.Item>
    </Form>
    </div>
    </div>
  );
};

export default Login2;
